package cn.ivicar.mapper.service.impl;

import java.util.List;
import java.util.Map;

import cn.ivicar.mapper.replicable.ReplicableSqlSessionFactory;
import cn.ivicar.mapper.service.DbManager;
import cn.ivicar.mapper.utils.AntiInjection;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import com.google.inject.Inject;

public class DbManagerImpl implements DbManager {
    private static Logger logger = Logger.getLogger(DbManagerImpl.class);

    @Inject
    protected ReplicableSqlSessionFactory sqlSessionFactory;

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public List<Map> list(String sqlKey, Object parameter) {
        SqlSession session = this.sqlSessionFactory.openReplicableSqlSession(false);
        try {
            if(parameter instanceof Map){
                Map paraMap = (Map)parameter;
                for (Object key : paraMap.keySet()) {
                    Object result = paraMap.get(key);
                    if (result instanceof String) {
                        boolean flag = AntiInjection.check((String) result);
                        if (!flag) {
                            paraMap.remove(key);
                            logger.info("未通过防SQL检查，移除该参数[" + key.toString() + "][" + result.toString() + "]");
                        }
                    }
                }
            }

            return session.selectList(sqlKey, parameter);
        } finally {
            session.close();
        }
    }

    public ReplicableSqlSessionFactory getSqlSessionFactory() {
        return this.sqlSessionFactory;
    }
}
